﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.SessionState;
using OLTS.DATA_SERVICE;
using OLTS.MODEL;
using OLTS.MODEL.Custom_Model;
using OLTS.WEB.BaseClass;

namespace ONTS.WEB.Service
{
    /// <summary>
    /// Summary description for TimeSheetTBankService
    /// </summary>
    public class TimeSheetTBankService : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            HttpRequest request = context.Request;
            HttpResponse response = context.Response;
            var currentuser = BaseService.LOGIN.EMPLOYEE_ID;
            var date = request.QueryString["date"].ToString();
            System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
            var dt = Convert.ToDateTime(date);
            var cmd = new TimeSheet_Service();
            var listDB = cmd.GetCurrentUserandDate(currentuser);
           
            foreach (var parent in listDB)
            {
                var obj = DataSource.Where(x => x.ID == parent.ID).FirstOrDefault();
                if (obj == null)
                {
                    DataSource.Add(parent);
                }

            }

            if (request["oper"] == "add")
            {
                var childobj = new OLTS.MODEL.OTS_WORK_DETAIL();
                childobj.SEQ = Utility.CheckInt(request["SEQ"]);
                childobj.AMOUNT_OF_TIME = Utility.CheckInt(request["AMOUNT_OF_TIME"]);
                childobj.AMOUNT_OF_TIME_OVER_TIME = Utility.CheckInt(request["AMOUNT_OF_TIME_OVER_TIME"]);
                childobj.DETAIL = request["DETAIL"];
                if (request["LEAVE_ID"] == "0")
                {
                    childobj.LEAVE_ID = null;
                }
                else
                {
                    childobj.LEAVE_ID = Utility.CheckInt(request["LEAVE_ID"]);
                    childobj.LEAVE_NM = GetLeaveNamebyID(childobj.LEAVE_ID);
                    childobj.AMOUNT_OF_LEAVE = Utility.CheckInt(request["AMOUNT_OF_LEAVE"]);
                }
                childobj.REQUEST_ID = request["REQUEST_ID"];
                childobj.APPLICATION_ID = request["APPLICATION_ID"];
                childobj.APPLICATION_NAME = request["APPLICATION_NAME"];
                childobj.FUNCTION_NAME = request["FUNCTION_NAME"];
                childobj.REMARK = request["REMARK"];
                childobj.ROLE = request["ROLE"];
                childobj.CREATED = DateTime.Now;
                childobj.CREATE_BY = currentuser;
                childobj.Action = OLTS.MODEL.ActionEnum.Create;
                var parent = DataSource.Where(x => x.EMPLOYEE_ID == currentuser && x.DATE == Convert.ToDateTime(date)).FirstOrDefault();
                if (parent != null)
                {
                    var childlist = parent.OTS_WORK_DETAIL;
                    childlist.Add(childobj);
                    if (parent.Action != ActionEnum.Create)
                    {
                        parent.Action = ActionEnum.Update;
                    }

                }
                else
                {
                    var holiday = isHoliday();
                    var childList = new List<OTS_WORK_DETAIL>();
                    parent = new  OTS_TIME_SHEET();
                    parent.DATE = dt;
                    parent.EMPLOYEE_ID = currentuser;
                    if (holiday != null)
                    {
                        parent.HOLIDAY_ID = holiday.ID;
                    }
                    parent.CREATE_BY = currentuser;
                    parent.CREATED = DateTime.Now;
                    childList.Add(childobj);
                    parent.OTS_WORK_DETAIL = childList;
                    parent.Action = ActionEnum.Create;
                    DataSource.Add(parent);
                }
            }
            else
            {
                if (request["oper"] == "del")
                {
                    foreach (var parent in DataSource.ToList())
                    {
                        var childlist = parent.OTS_WORK_DETAIL;
                        var id = Convert.ToInt32(request["ID"]);
                        var obj = childlist.Where(x => x.ID == id).FirstOrDefault();
                        if (obj != null)
                        {
                            var details = obj.DETAIL;
                            obj.Action = ActionEnum.Delete;
                            if (hasLeave(details))
                            {
                                parent.LEAVE_ID = null;
                            }
                            parent.Action = ActionEnum.Update;
                            break;
                        }
                    }
                }
                else if (request["oper"] == "edit")
                {
                    var id = Convert.ToInt32(request["ID"]);
                    foreach (var parent in DataSource.ToList())
                    {
                        var childlist = parent.OTS_WORK_DETAIL;
                        var obj = childlist.Where(x => x.ID == id).FirstOrDefault();
                        if (obj != null)
                        {
                            obj.AMOUNT_OF_TIME = Utility.CheckInt(request["AMOUNT_OF_TIME"]);
                            obj.AMOUNT_OF_TIME_OVER_TIME = Utility.CheckInt(request["AMOUNT_OF_TIME_OVER_TIME"]);
                            obj.DETAIL = request["DETAIL"];
                            obj.START_TIME = request["START_TIME"];
                            obj.END_TIME = request["END_TIME"];
                            obj.REQUEST_ID = request["REQUEST_ID"];
                            if (request["LEAVE_ID"] == "0")
                            {
                                obj.LEAVE_ID = null;
                            }
                            else
                            {
                                obj.LEAVE_ID = Utility.CheckInt(request["LEAVE_ID"]);
                                obj.LEAVE_NM = GetLeaveNamebyID(obj.LEAVE_ID);
                                obj.AMOUNT_OF_LEAVE = Utility.CheckInt(request["AMOUNT_OF_LEAVE"]);
                            }
                            obj.LEAVE_NM = GetLeaveNamebyID(obj.LEAVE_ID);
                            obj.APPLICATION_ID = request["APPLICATION_ID"];
                            obj.APPLICATION_NAME = request["APPLICATION_NAME"];
                            obj.FUNCTION_NAME = request["FUNCTION_NAME"];
                            obj.REMARK = request["REMARK"];
                            obj.ROLE = request["ROLE"];
                            obj.CREATED = DateTime.Now;
                            obj.CREATE_BY = currentuser;
                            obj.Action = ActionEnum.Update;
                            parent.Action = ActionEnum.Update;
                            break;
                        }
                    }
                }
            }

            var pObj = DataSource.Where(x => x.DATE == dt && x.EMPLOYEE_ID == currentuser).FirstOrDefault();
            var resultList = new List<OLTS.MODEL.OTS_WORK_DETAIL>();
            if (pObj != null)
            {
                var row = 0;
                var chiList = pObj.OTS_WORK_DETAIL;
                foreach (var item in chiList)
                {
                    if (item.Action != ActionEnum.Delete)
                    {
                        row = row + 1;
                        var obj = new OLTS.MODEL.OTS_WORK_DETAIL();
                        obj.ID = item.ID; 
                        obj.RowIndex = row;
                        obj.SEQ = row;
                        obj.LEAVE_ID = item.LEAVE_ID;
                        obj.AMOUNT_OF_LEAVE = item.AMOUNT_OF_LEAVE;
                        obj.AMOUNT_OF_TIME = item.AMOUNT_OF_TIME;
                        obj.AMOUNT_OF_TIME_OVER_TIME = item.AMOUNT_OF_TIME_OVER_TIME;
                        obj.DETAIL = item.DETAIL;
                        obj.LEAVE_NM = GetLeaveNamebyID(item.LEAVE_ID);
                        obj.REQUEST_ID = item.REQUEST_ID;
                        obj.APPLICATION_ID = item.APPLICATION_ID;
                        obj.APPLICATION_NAME = item.APPLICATION_NAME;
                        obj.FUNCTION_NAME = item.FUNCTION_NAME;
                        obj.REMARK = item.REMARK;
                        obj.ROLE = item.ROLE;
                        resultList.Add(obj);
                    }
                }
            }

            int total = resultList.Count == 0 ? 1 : (int)Math.Ceiling((double)resultList.Count / 10);

            var jsonData = new
            {
                total = total,
                page = request["page"],
                records = resultList.Count,
                rows = resultList.Skip(Convert.ToInt16(request["page"]) * 10 - 10).Take(10)
            };

            response.Write(new JavaScriptSerializer().Serialize(jsonData));
        }

        public List<OLTS.MODEL.OTS_TIME_SHEET> DataSource
        {
            get
            {
                var d = (List<OLTS.MODEL.OTS_TIME_SHEET>)HttpContext.Current.Session["timesheet"];
                if (d == null)
                {
                    d = new List<OLTS.MODEL.OTS_TIME_SHEET>();
                    HttpContext.Current.Session["timesheet"] = d;
                }
                return d;
            }
            set
            {
                HttpContext.Current.Session["timesheet"] = value;
            }
        }
         
        private OTS_HOLIDAY isHoliday()
        {

            var currentuser = BaseService.LOGIN.EMPLOYEE_ID;
            var site = BaseService.PROJECT.SITE_ID;
            var yr = DateTime.Now.Year.ToString();
            var cmd = new Holiday_Service(yr, Convert.ToInt16(site));
            var result = cmd.GetListHoliday();
            var isholiday = result.Where(x => x.DATE == DateTime.Now.Date).FirstOrDefault();
            if (isholiday != null)
            {
                return isholiday;
            }
            else
            {
                return null;
            }

        }

        private List<OTS_LEAVE> _ots_leave = new List<OTS_LEAVE>();

        private string GetLeaveNamebyID(int? leave_id)
        {
            if (_ots_leave.Count == 0)
            {
                var cmd = new LEAVE_Service();
                _ots_leave = cmd.GetAll().ToList();
            }

            if (_ots_leave.Count > 0)
            {
                var obj = _ots_leave.Where(x => x.ID == leave_id).FirstOrDefault();
                if (obj != null)
                {
                    return obj.NAME;
                }
                else
                {
                    return "";
                }
            }
            return "";
        }

        private bool hasLeave(string leave)
        {
            var cmd = new LEAVE_Service();
            var result = cmd.GetAll().Where(x => x.NAME == leave).FirstOrDefault();
            if (result != null)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}